<template>
  <view class="note-detail-container">
    <!-- 顶部栏 -->
    <view class="header">
      <view class="header-left">
        <view class="back-btn" @tap="goBack">
          <text class="back-icon">←</text>
        </view>
        <text class="header-title">笔记详情</text>
      </view>
      <view class="header-actions">
        <view class="action-btn" @tap="shareNote">
          <text class="action-icon">📤</text>
        </view>
        <view class="action-btn" @tap="showMoreActions">
          <text class="action-icon">•••</text>
        </view>
      </view>
    </view>
    
    <!-- 笔记内容编辑区域 -->
    <view class="note-content-area">
      <input type="text" placeholder="笔记标题" v-model="note.title" class="note-title-input"/>
      <textarea placeholder="开始输入笔记内容..." v-model="note.content" class="note-content-input" auto-height="true" show-confirm-bar="true"/>
      
      <!-- 底部操作栏 -->
      <view class="bottom-actions">
        <view class="category-selector" @tap="showCategoryMenu">
          <text class="category-icon">{{ getCategoryIcon(note.category) }}</text>
          <text class="category-name">{{ getCategoryName(note.category) }}</text>
        </view>
        
        <view class="save-btn" @tap="saveNote">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>
    
    <!-- 笔记历史记录 -->
    <view class="history-section" v-if="noteHistory.length > 0">
      <text class="history-title">编辑历史</text>
      <view class="history-list">
        <view v-for="(history, index) in noteHistory" :key="index" class="history-item">
          <text class="history-date">{{ history.date }}</text>
          <text class="history-preview">{{ getHistoryPreview(history.content) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 添加图片按钮 -->
    <view class="image-upload-section">
      <text class="section-title">添加图片</text>
      <view class="image-upload-area">
        <view class="upload-btn" @tap="chooseImage">
          <text class="upload-icon">+</text>
          <text class="upload-text">添加图片</text>
        </view>
        
        <view v-for="(image, index) in noteImages" :key="index" class="image-preview">
          <image :src="image" mode="aspectFill" class="preview-image"/>
          <view class="delete-image-btn" @tap="deleteImage(index)">
            <text class="delete-icon">×</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      note: {
        id: '',
        title: '',
        content: '',
        date: '',
        category: 'life'
      },
      noteHistory: [],
      noteImages: [],
      originalNote: null
    };
  },
  onLoad(options) {
    // 模拟从路由参数获取笔记ID和标题
    if (options.id) {
      this.note.id = options.id;
      
      // 优先使用路由参数中的完整数据
      if (options.title) {
        this.note.title = decodeURIComponent(options.title);
      }
      if (options.content) {
        this.note.content = decodeURIComponent(options.content);
      }
      if (options.category) {
        this.note.category = options.category;
      }
      if (options.date) {
        this.note.date = decodeURIComponent(options.date);
      }
      
      // 如果没有完整数据，再从本地加载
      if (!options.content) {
        this.loadNoteData();
      } else {
        // 有完整数据时直接加载相关资源
        this.loadNoteHistory();
        this.loadNoteImages();
      }
    } else {
      // 新建笔记
      this.note.id = Date.now().toString();
      this.note.date = this.getCurrentTime();
    }
    
    // 保存原始笔记数据用于比较
    this.originalNote = JSON.parse(JSON.stringify(this.note));
  },
  onShow() {
    // 每次显示页面时检查笔记是否有修改
    this.checkNoteChanges();
  },
  methods: {
    // 加载笔记数据
    loadNoteData() {
      // 这里模拟从本地存储加载笔记数据
      // 实际项目中应该从数据库或本地存储获取
      setTimeout(() => {
        // 模拟数据
        const mockNotes = [
          {
            id: '1',
            title: '小程序开发要点',
            content: '1. 登录授权流程\n2. 权限请求策略\n3. 组件化开发方案\n4. 数据存储管理\n5. 性能优化技巧',
            date: '今天 10:30',
            category: 'work'
          },
          {
            id: '2',
            title: '产品需求文档解读',
            content: '主要功能点：\n- 用户认证系统\n- 数据可视化展示\n- 移动端适配优化\n- 第三方服务集成',
            date: '今天 09:15',
            category: 'work'
          },
        ];
        
        const foundNote = mockNotes.find(note => note.id === this.note.id);
        if (foundNote) {
          this.note = { ...foundNote };
          this.loadNoteHistory();
          this.loadNoteImages();
        }
      }, 200);
    },
    
    // 加载笔记历史记录
    loadNoteHistory() {
      // 模拟加载编辑历史
      this.noteHistory = [
        {
          id: '1',
          date: '今天 10:25',
          content: '1. 登录授权流程\n2. 权限请求策略\n3. 组件化开发方案'
        },
        {
          id: '2',
          date: '今天 10:10',
          content: '1. 登录授权流程\n2. 权限请求策略'
        }
      ];
    },
    
    // 加载笔记图片
    loadNoteImages() {
      // 模拟加载图片
      if (this.note.id === '1') {
        // 使用网络图片作为示例
        this.noteImages = [
          'https://img01.yzcdn.cn/vant/apple-1.jpg',
          'https://img01.yzcdn.cn/vant/apple-2.jpg'
        ];
      }
    },
    
    // 返回上一页
    goBack() {
      // 检查是否有未保存的修改
      if (this.hasUnsavedChanges()) {
        uni.showModal({
          title: '提示',
          content: '您有未保存的修改，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack();
            }
          }
        });
      } else {
        uni.navigateBack();
      }
    },
    
    // 检查笔记是否有修改
    checkNoteChanges() {
      // 实现检查逻辑
    },
    
    // 检查是否有未保存的修改
    hasUnsavedChanges() {
      return this.note.title !== this.originalNote.title || 
             this.note.content !== this.originalNote.content ||
             this.note.category !== this.originalNote.category;
    },
    
    // 保存笔记
    saveNote() {
      if (!this.note.title.trim()) {
        uni.showToast({
          title: '请输入笔记标题',
          icon: 'none'
        });
        return;
      }
      
      // 更新笔记日期
      this.note.date = this.getCurrentTime();
      
      // 模拟保存操作
      setTimeout(() => {
        // 保存到本地存储或后端
        this.originalNote = JSON.parse(JSON.stringify(this.note));
        
        // 显示保存成功提示
        uni.showToast({
          title: '保存成功'
        });
        
        // 如果是新建笔记，保存后返回列表页
        if (this.$route.query.isNew) {
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      }, 500);
    },
    
    // 显示分类选择菜单
    showCategoryMenu() {
      const categories = [
        { id: 'work', name: '工作', icon: '💼' },
        { id: 'study', name: '学习', icon: '📚' },
        { id: 'life', name: '生活', icon: '🏠' },
        { id: 'idea', name: '创意', icon: '💡' }
      ];
      
      const itemList = categories.map(cat => `${cat.icon} ${cat.name}`);
      
      uni.showActionSheet({
        itemList: itemList,
        success: (res) => {
          if (res.tapIndex !== -1) {
            this.note.category = categories[res.tapIndex].id;
          }
        }
      });
    },
    
    // 获取分类名称
    getCategoryName(category) {
      const categoryMap = {
        'work': '工作',
        'study': '学习',
        'life': '生活',
        'idea': '创意'
      };
      return categoryMap[category] || '其他';
    },
    
    // 获取分类图标
    getCategoryIcon(category) {
      const iconMap = {
        'work': '💼',
        'study': '📚',
        'life': '🏠',
        'idea': '💡'
      };
      return iconMap[category] || '📝';
    },
    
    // 分享笔记
    shareNote() {
      uni.showModal({
        title: '分享笔记',
        content: '选择分享方式',
        confirmText: '分享给朋友',
        cancelText: '生成图片分享',
        success: (res) => {
          if (res.confirm) {
            // 分享给朋友
            this.shareToFriend();
          } else if (res.cancel) {
            // 生成图片分享
            this.generateShareImage();
          }
        }
      });
    },
    
    // 分享给朋友
    shareToFriend() {
      uni.showToast({
        title: '分享给朋友功能已触发',
        icon: 'none'
      });
      // 实际项目中应该调用微信分享API
    },
    
    // 生成图片分享
    generateShareImage() {
      uni.showLoading({
        title: '生成图片中...'
      });
      
      // 模拟生成图片
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '图片生成成功，已保存到相册',
          icon: 'success'
        });
      }, 1500);
    },
    
    // 显示更多操作
    showMoreActions() {
      uni.showActionSheet({
        itemList: ['删除笔记', '复制内容', '导出笔记'],
        itemColor: '#ff4d4f',
        success: (res) => {
          if (res.tapIndex === 0) {
            this.deleteNote();
          } else if (res.tapIndex === 1) {
            this.copyNoteContent();
          } else if (res.tapIndex === 2) {
            this.exportNote();
          }
        }
      });
    },
    
    // 删除笔记
    deleteNote() {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除"${this.note.title}"吗？`,
        confirmText: '删除',
        confirmColor: '#ff4d4f',
        success: (res) => {
          if (res.confirm) {
            // 模拟删除操作
            setTimeout(() => {
              uni.showToast({
                title: '删除成功'
              });
              
              // 删除后返回列表页
              setTimeout(() => {
                uni.navigateBack();
              }, 1000);
            }, 500);
          }
        }
      });
    },
    
    // 复制笔记内容
    copyNoteContent() {
      // 复制标题和内容到剪贴板
      const content = `${this.note.title}\n\n${this.note.content}`;
      
      // 模拟复制操作
      uni.setClipboardData({
        data: content,
        success: () => {
          uni.showToast({
            title: '内容已复制到剪贴板'
          });
        }
      });
    },
    
    // 导出笔记
    exportNote() {
      uni.showLoading({
        title: '导出中...'
      });
      
      // 模拟导出操作
      setTimeout(() => {
        uni.hideLoading();
        uni.showModal({
          title: '导出成功',
          content: '笔记已导出为文本文件，是否保存到手机？',
          confirmText: '保存',
          success: (res) => {
            if (res.confirm) {
              uni.showToast({
                title: '文件已保存到下载文件夹',
                icon: 'success'
              });
            }
          }
        });
      }, 1500);
    },
    
    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 9 - this.noteImages.length, // 最多选择9张图片
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 将选择的图片添加到列表中
          this.noteImages = [...this.noteImages, ...res.tempFilePaths];
        }
      });
    },
    
    // 删除图片
    deleteImage(index) {
      this.noteImages.splice(index, 1);
    },
    
    // 获取历史记录预览
    getHistoryPreview(content) {
      // 截取前50个字符作为预览
      return content.length > 50 ? content.substring(0, 50) + '...' : content;
    },
    
    // 获取当前时间
    getCurrentTime() {
      const now = new Date();
      const hour = now.getHours().toString().padStart(2, '0');
      const minute = now.getMinutes().toString().padStart(2, '0');
      
      // 判断是否是今天
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      if (now >= today) {
        return `今天 ${hour}:${minute}`;
      } else if (now >= yesterday) {
        return `昨天 ${hour}:${minute}`;
      } else {
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const date = now.getDate().toString().padStart(2, '0');
        return `${month}-${date} ${hour}:${minute}`;
      }
    }
  }
};
</script>

<style scoped>
.note-detail-container {
  height: 100vh;
  background-color: #f8f9fc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
}

.back-btn {
  margin-right: 20rpx;
}

.back-icon {
  font-size: 32rpx;
  color: #333;
}

.header-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.action-btn {
  margin-left: 30rpx;
}

.action-icon {
  font-size: 32rpx;
  color: #333;
}

/* 笔记内容区域 */
.note-content-area {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.note-title-input {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
  padding: 10rpx 0;
  margin-bottom: 20rpx;
  border: none;
  outline: none;
  width: 100%;
}

.note-content-input {
  font-size: 32rpx;
  color: #666;
  line-height: 1.8;
  padding: 0;
  border: none;
  outline: none;
  width: 100%;
  min-height: 300rpx;
}

/* 底部操作栏 */
.bottom-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.category-selector {
  display: flex;
  align-items: center;
  padding: 15rpx 25rpx;
  background-color: #f2f2f2;
  border-radius: 40rpx;
}

.category-icon {
  font-size: 28rpx;
  margin-right: 10rpx;
}

.category-name {
  font-size: 28rpx;
  color: #666;
}

.save-btn {
  padding: 15rpx 40rpx;
  background-color: #667eea;
  border-radius: 40rpx;
}

.save-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}

/* 历史记录区域 */
.history-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.history-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.history-item {
  padding: 20rpx;
  background-color: #f8f9fc;
  border-radius: 15rpx;
}

.history-date {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 10rpx;
  display: block;
}

.history-preview {
  font-size: 28rpx;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 图片上传区域 */
.image-upload-section {
  padding: 30rpx;
  background-color: #fff;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.image-upload-area {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  background-color: #f2f2f2;
  border-radius: 15rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 48rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.image-preview {
  width: 160rpx;
  height: 160rpx;
  border-radius: 15rpx;
  overflow: hidden;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-image-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 50rpx;
  height: 50rpx;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom-left-radius: 15rpx;
}

.delete-icon {
  font-size: 36rpx;
  color: #fff;
  line-height: 1;
}
</style>